<?php
namespace app\store\controller\food\user;

use app\store\controller\food\Controller;
use think\facade\Cache;
use app\store\model\food\User as UserModel;
use app\store\model\food\Shop as ShopModel;
use app\store\model\food\Goods as GoodsModel;
use think\facade\View;

/**
 * 购物车控制器
 */
class Cart extends Controller
{
    /**
     * 购物车列表
     */
    public function index($shop_id=0,$search='')
    {
        $search = trim($search);
    	if($this->shop_mode == 10){
            $shop[0] = ShopModel::detail($this->shop_id);
        }else{
            $filter = [];
            $shop_id > 0 && $filter['shop_id'] = $shop_id;
        	$shop = (new ShopModel)->where($filter)->select();
        }
        $filter = [];
        $model = (new UserModel)->order('user_id','desc');
        if(!empty($search)){
            //是否是数字
            if(is_numeric($search)){   
                //是否是手机号
                if(is_phone($search)){
                    $filter['phone'] = $search;
                }else{
                    $filter['user_id'] = $search;
                }
            }else{
               //不是数字   
                $model->where('nickname','like',"%{$search}%");
            }
        }
        $user = $model->where($filter)->select();
        
        $list = array();
        for($n=0;$n<sizeof($user);$n++){
    		for($m=0;$m<sizeof($shop);$m++){
    			if($cart = Cache::get('cart_' . $user[$n]['user_id'] . '_' . $shop[$m]['shop_id'])){
    				//读取数据键名
    				$key = array_keys($cart);
    				//循环获取商品详情
    				$goods = array();
    				for($k=0;$k<sizeof($key);$k++){
    					if($detail = GoodsModel::detail($cart[$key[$k]]['goods_id'])){
    						$detail['goods_num'] = $cart[$key[$k]]['goods_num'];
    						array_push($goods,$detail);
    					}
    				}
    				$new['user'] = $user[$n];
    				$new['shop'] = $shop[$m];
    				$new['goods'] = $goods;
    				array_push($list,$new);
    			}	
    		}
    	}
    	$model = new ShopModel;
        $category = $model->getList(false);
        return View::fetch('index', compact('list','category','shop_id','search'));
    }
}
